package com.shanghaionstar.discover.geofence.presenter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Message;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;

import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.MyPost;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.mvp.base.core.PermissionCall;
import com.onstar.cn.mag.poi.FavoriteEntity;
import com.onstar.cn.sqlite.entities.PoiSearchHistory;
import com.onstar.cn.map.MapSearch;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.map.common.PoiType;
import com.onstar.cn.map.common.SearchResults;
import com.onstar.cn.map.util.MessageHandler;
import com.onstar.cn.map.util.QueryOptions;
import com.shanghaionstar.R;
import com.shanghaionstar.discover.geofence.iview.IGeofenceCenterView;
import com.shanghaionstar.discover.geofence.service.GeofenceCenterService;
import com.shanghaionstar.sqlite.SearchHistoryImpl;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.LoadCityList;
import com.shanghaionstar.utils.MyLocationUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 7828wc on 16/7/21.
 */
public class GeofenceCenterPresenter extends BasePresenter<List<FavoriteEntity>> {
    private BaseActivity mContext;

    private int lastItemIndex = 0;
    private List<PoiItemInfo> searchPoiList = new ArrayList<PoiItemInfo>();
    //搜索历史
    private List<PoiSearchHistory> searchHistoryList;
    private SearchHistoryImpl searchHistoryImpl;
//    private ProgressDialog loadingDialog;
    private MapSearch mapSearch;
    private boolean isNextPage = false;
    private boolean isLocationing = false;
    private MyLocationUtil myLoationUtil;
    private PoiItemInfo currentLocationPoi = null;
    private boolean isSearching = false;//标示是否正在搜索

    public GeofenceCenterPresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    public void setNextPage(List<PoiItemInfo> resultList) {
        isNextPage = resultList.size() >= Constants.POI_NUMBER;
    }

    public void setLastItemIndex(int first, int vis) {
        lastItemIndex = first + vis;
    }

    public void onScrollStateChanged(int scrollState, int count) {
        if (!isNextPage) {
            return;
        }
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                && lastItemIndex == count) {
            try {
                mapSearch.getNextPage();
                isNextPage = false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void showMore(boolean isLoadingMore, List<PoiItemInfo> resultList) {
        if (!isLoadingMore) {
            if (resultList != null && resultList.size() <= 0) {
                if (searchPoiList != null)
                    searchPoiList.clear();
                ((IGeofenceCenterView) view).showNoData();
                return;
            }
            this.searchPoiList = new ArrayList<PoiItemInfo>();
            this.searchPoiList.addAll(resultList);
            if(view instanceof IGeofenceCenterView){
                ((IGeofenceCenterView) view).showPoiList(searchPoiList);
            }
        } else {
            searchPoiList.addAll(resultList);
            ((IGeofenceCenterView) view).notifyChange();
        }
    }

    public void myLocationClick() {
        if (currentLocationPoi != null && !CommonUtil.isNull(currentLocationPoi.getTitle())) {
            returnLevel(currentLocationPoi);
        } else {
            AlertDialogUtil.showAlertDialog(mContext, R.string.dialog_warning,
                    R.string.poi_no_gps_signal);
        }
    }

    @Override
    public void setView(IMVPView<List<FavoriteEntity>> view) {
        super.setView(view);
        this.view = view;
        mContext = (BaseActivity) view.onActivity();
        baseService = new GeofenceCenterService(mContext);
    }


    public void init() {
        if (searchHistoryImpl == null)
            searchHistoryImpl = new SearchHistoryImpl(mContext);
        mapSearch = new MapSearch(mContext, null, new MessageHandler(null) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case com.onstar.cn.map.common.Constants.SEARCH_RESULT:
                        SearchResults result = (SearchResults) msg.obj;
                        if (view instanceof IGeofenceCenterView) {
                            ((IGeofenceCenterView) view).showDatas(result.getResultList(), result.getPageIndex() > 0);
                        }
                        break;
                    case com.onstar.cn.map.common.Constants.SEARCH_ERRORS:
                        AlertDialogUtil.showAlertDialog(mContext, R.string.dialog_warning, R.string.poi_no_search);
                        break;
                    case com.onstar.cn.map.common.Constants.REVERSE_GEOCODE_RESULT:
                        PoiItemInfo poi = (PoiItemInfo) msg.obj;
                        String mSelectCity = poi.getCityName();
                        if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
                            LoadCityList loadFile = new LoadCityList(mContext);
                            poi.setCityName(loadFile.findByZhCity(mSelectCity));
                        }
                        poi.setTitle(mContext.getString(R.string.nav_set_my_location));
                        currentLocationPoi = poi;
                        break;
                    default:
                        break;
                }
                view.setLoading(false);
//                if (loadingDialog != null && loadingDialog.isShowing()) {
//                    loadingDialog.dismiss();
//                }
//                isSearching = false;
            }
        });
    }

    public void search(String searchText, EditText editText) {
//        if (isSearching) return;
//        isSearching = true;
        ((InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(editText.getWindowToken(), 0);
        if (CommonUtil.isNull(searchText)) {
            AlertDialogUtil.showAlertDialog(mContext, R.string.poi_destination_title_str,
                    R.string.poi_not_search_not_condition);
        } else {
            if (currentLocationPoi != null) {
                view.setLoading(true);
//                ((IGeofenceCenterView)view).showMyLoading();
                String city = currentLocationPoi.getCityName();
                QueryOptions options = new QueryOptions();
                options.setiPageNumber(0);
                options.setiPageCount(20);
                mapSearch.searchByName(searchText, PoiType.All, city, options);
            } else {
                AlertDialogUtil.showAlertDialog(mContext, R.string.dialog_warning,
                        isLocationing ? R.string.poi_not_my_location_str : R.string.poi_no_gps_signal);
            }
        }
    }

   public void onSuccess(List<FavoriteEntity> favoriteEntitiesList){
       if (!CommonUtil.isNull(favoriteEntitiesList)) {
           if (searchPoiList != null && searchPoiList.size() > 0) {
               searchPoiList.clear();
           }
//           List<FavoriteEntity> favoriteEntitiesList = JsonParseUtil.JsonToBean(FavoriteEntity.class, json);
           if (favoriteEntitiesList != null && favoriteEntitiesList.size() > 0) {
               for (FavoriteEntity favoriteEntity : favoriteEntitiesList) {
                   PoiItemInfo info = new PoiItemInfo();
                   info.setTitle(favoriteEntity.getPoiName());
                   info.setCityName(favoriteEntity.getCityCode());
                   info.setCityCode(favoriteEntity.getPoiCityCode());
                   info.setId(favoriteEntity.getFavoriteDestinationID());
                   info.setLatitude(favoriteEntity.getPoiCoordinate().getLatitude());
                   info.setLongitude(favoriteEntity.getPoiCoordinate().getLongitude());
                   info.setAddress(favoriteEntity.getPoiAddress());
                   info.setTelphone(favoriteEntity.getPoiPhoneNumber());
                   info.setTypeDes(favoriteEntity.getPoiCatetory());
                   searchPoiList.add(info);
               }
           }
       }
       ((IGeofenceCenterView)view).onSuccess(searchPoiList);
   }

    public void showHistoryDatas() {
        searchHistoryList = searchHistoryImpl.getSearchList();
        if(view instanceof IGeofenceCenterView ){
            ((IGeofenceCenterView) view).showHistoryDatas(searchHistoryList);
        }
    }

    public void onItemClick(int position) {
        PoiSearchHistory poiSearchHistory = searchHistoryList.get(position);
        PoiItemInfo poiItemInfo = new PoiItemInfo();
        poiItemInfo.setTitle(poiSearchHistory.getName());
        poiItemInfo.setThreadId(poiSearchHistory.getSearchtime());
        poiItemInfo.setAddress(poiSearchHistory.getAddress());
        poiItemInfo.setLatitude(poiSearchHistory.getLat());
        poiItemInfo.setLongitude(poiSearchHistory.getLon());
        poiItemInfo.setCityName(poiSearchHistory.getCityname());
        poiItemInfo.setTelphone(poiSearchHistory.getPhone());

        returnLevel(poiItemInfo);
    }

    public void returnLevel(PoiItemInfo poiItemInfo) {
        Intent intent = new Intent();
        intent.putExtra("poiItemInfo", poiItemInfo);
        mContext.setResult(Activity.RESULT_OK, intent);
        mContext.finish();
    }

    public void poilistItemClick(int position) {
        PoiItemInfo poiItemInfo = searchPoiList.get(position);
        searchHistoryImpl.saveSearchHistory(poiItemInfo);
        returnLevel(poiItemInfo);
    }

    public void choosePoint() {
        PoiItemInfo vehiclePoiItem = new PoiItemInfo();
        vehiclePoiItem.setTitle(mContext.getString(R.string.poi_route_vehicle_str));
        vehiclePoiItem.setAddress(mContext.getString(R.string.poi_route_vehicle_str));
        vehiclePoiItem.setLatitude(-1);
        vehiclePoiItem.setLongitude(-1);
        returnLevel(vehiclePoiItem);
    }

    public void clearHistory() {
        searchHistoryImpl.deleteAll();
        searchHistoryList.clear();
    }

    /**
     * Get current location and current city
     */
    public void getLocationAndCity() {
        mContext.requestRunTimePermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionCall() {
            @Override
            public void requestSuccess() {
                MyLocationUtil.LocationResult locationResult = new MyLocationUtil.LocationResult() {
                    @Override
                    public void gotLocation(Location location) {
                        if (location != null) {
                            isLocationing = false;
                            mapSearch.geoCoderGps(location.getLatitude(), location.getLongitude());
                        } else {
                            isLocationing = false;
                            MyPost.post(new Runnable() {
                                @Override
                                public void run() {
                                    AlertDialogUtil.showAlertDialog(mContext, R.string.dialog_warning,
                                            isLocationing ? R.string.poi_not_my_location_str : R.string.poi_no_gps_signal);
                                }
                            });
                        }
                    }
                };

                if (myLoationUtil == null) {
                    myLoationUtil = new MyLocationUtil(mContext, locationResult);
                }
                if (myLoationUtil != null) {
                    isLocationing = true;
                    myLoationUtil.initMyLocation();
                }
            }

            @Override
            public void refused() {

            }
        });

    }

}
